package com.asia5b.a5mall.goods.adapter

import android.net.Uri
import androidx.recyclerview.widget.GridLayoutManager
import androidx.recyclerview.widget.RecyclerView
import android.text.Html
import android.text.TextUtils
import android.view.View
import android.view.ViewGroup
import android.webkit.WebSettings
import android.webkit.WebView
import android.widget.ImageView
import android.widget.LinearLayout
import android.widget.RatingBar
import android.widget.TextView
import androidx.databinding.DataBindingUtil
import androidx.databinding.ViewDataBinding
import com.asia5b.a5bmall.resource.ResString
import com.asia5b.a5bmall.same.dialog.ChoiceCurrencyDialog
import com.asia5b.a5mall.goods.R
import com.asia5b.a5mall.goods.activity.GoodsDetail2Activity
import com.asia5b.a5mall.goods.databinding.ItemGoodsdetailComments2Binding
import com.asia5b.a5mall.goods.databinding.ItemGoodsdetailDetailBinding
import com.asia5b.a5mall.goods.databinding.ItemGoodsdetailShopBinding
import com.asia5b.a5mall.middleware.config.CountrysRepository
import com.asia5b.a5mall.middleware.model.base.ResultModel
import com.asia5b.a5mall.middleware.model.bean.GoodsDetailItemEntityIml
import com.asia5b.a5mall.middleware.model.goods.Goods2CommenModel
import com.asia5b.a5mall.middleware.model.goods.Goods2SkuModel
import com.asia5b.a5mall.middleware.model.member.CouponModel
import com.asia5b.a5mall.middleware.model.member.CurrencyModel
import com.asia5b.a5mall.middleware.model.member.PromotionModel
import com.asia5b.a5mall.middleware.model.shop.AbsGoodsModel
import com.asia5b.a5mall.middleware.model.shop.AbsShopModel
import com.asia5b.a5mall.middleware.model.shop.Goods2GalleryBean
import com.asia5b.a5mall.middleware.utils.*
import com.asia5b.a5mall.middleware.utils.glide.BannerImageImlAdapter
import com.asia5b.a5mall.middleware.widget.GridSpacingItemDecoration
import com.chad.library.adapter.base.BaseMultiItemQuickAdapter
import com.chad.library.adapter.base.viewholder.BaseDataBindingHolder
import com.chad.library.adapter.base.viewholder.BaseViewHolder
import com.youth.banner.Banner
import com.youth.banner.indicator.CircleIndicator
import com.youth.banner.listener.OnPageChangeListener

/**
 * Created by zhangyuncai on 2019/12/24.
 */



class GoodsDetailInfoAdapter(
        val activity: GoodsDetail2Activity,
        val list: ArrayList<GoodsDetailItemEntityIml>
) : BaseMultiItemQuickAdapter<GoodsDetailItemEntityIml, BaseDataBindingHolder<*>>(list) {

    init {
        addItemType(GoodsDetailItemEntityIml.GoodsDetail_Gallery, R.layout.item_goodsdetail_gallery)
        addItemType(GoodsDetailItemEntityIml.GoodsDetail_Goods, R.layout.item_goodsdetail_detail)
        addItemType(GoodsDetailItemEntityIml.GoodsDetail_Spec, R.layout.item_goodsdetail_spec)
        addItemType(GoodsDetailItemEntityIml.GoodsDetail_Comments, R.layout.item_goodsdetail_comments2)
        addItemType(GoodsDetailItemEntityIml.GoodsDetail_Shop, R.layout.item_goodsdetail_shop)
        addItemType(GoodsDetailItemEntityIml.GoodsDetail_Coupon, R.layout.item_goodsdetail_coupon)
        addItemType(GoodsDetailItemEntityIml.GoodsDetail_Activity, R.layout.item_goodsdetail_activity)
        addItemType(GoodsDetailItemEntityIml.GoodsDetail_Introduce, R.layout.item_goodsdetail_introduce)
    }

    override fun convert(helper: BaseDataBindingHolder<*>, item2: GoodsDetailItemEntityIml) {
        helper.setIsRecyclable(false)
//        val viewDataBindingTag = helper.itemView.getTag(R.id.BaseQuickAdapter_databinding_support);
        if (item2.t != null) {
            val item = item2.t
            when (item2.itemType) {
                GoodsDetailItemEntityIml.GoodsDetail_Goods -> {
                    setDetailItemView(helper, item as AbsGoodsModel,helper.dataBinding as  ItemGoodsdetailDetailBinding)
                }
                GoodsDetailItemEntityIml.GoodsDetail_Gallery -> {
                    setGalleryItemView(helper, item as ArrayList<Goods2GalleryBean>)
                }
                GoodsDetailItemEntityIml.GoodsDetail_Spec -> {
                    setSpecItemView(helper, item as Goods2SkuModel)
                }
                GoodsDetailItemEntityIml.GoodsDetail_Comments -> {
                    if (item != null && item is Array<*> && item.size >= 2) {
                        val goods = item[0] as AbsGoodsModel
                        val commentResultModel = item[1] as ResultModel<ArrayList<Goods2CommenModel>>
                        setCommentsItemView(helper, goods, commentResultModel,helper.dataBinding as ItemGoodsdetailComments2Binding)
                    }
                }
                GoodsDetailItemEntityIml.GoodsDetail_Shop -> {
                    setShopItemView(helper, item as AbsShopModel,helper.dataBinding as ItemGoodsdetailShopBinding)
                }
                GoodsDetailItemEntityIml.GoodsDetail_Introduce -> {
                    setIntroduceItemView(helper, item as AbsGoodsModel)
                }
                GoodsDetailItemEntityIml.GoodsDetail_Coupon -> {
                    setCouponItemView(helper, item as CouponModel)
                }
                GoodsDetailItemEntityIml.GoodsDetail_Activity -> {
                    setPromotionItemView(helper, item as PromotionModel)
                }
            }
        }
    }

    fun setPromotionItemView(helper: BaseViewHolder, model: PromotionModel) {
        helper.setText(R.id.tv_promotion_content, model.getPromotionText())

    }

    fun setCouponItemView(helper: BaseViewHolder, couponModel: CouponModel) {
        helper.setText(R.id.tv_coupon_content, String.format(ResString.get(R.string.领立减_数_元优惠券), couponModel.coupon_price))

    }

    fun setIntroduceItemView(helper: BaseViewHolder, goods: AbsGoodsModel) {
        dddLog("setIntroduceItemView")
        var intro = goods!!.absGoodsShopIntro
//        var params = goods!!.param_list ?: arrayListOf()
        val webView = helper.getView<WebView>(R.id.web_goodsdetail)
        val localWebSettings = webView.getSettings()
        localWebSettings.useWideViewPort = true
        localWebSettings.loadWithOverviewMode = true
        localWebSettings.layoutAlgorithm = WebSettings.LayoutAlgorithm.NARROW_COLUMNS
        localWebSettings.javaScriptEnabled = true
        localWebSettings.setSupportZoom(true)
        localWebSettings.builtInZoomControls = true
        webView.isVerticalScrollBarEnabled = false
        webView.isHorizontalScrollBarEnabled = false
        webView.loadData(HtmlUtils.get.fitImageSize(intro), "text/html; charset=UTF-8", null);

    }

    fun setSpecItemView(helper: BaseViewHolder, item: Goods2SkuModel) {

        var spec_value_list_text = item.spec_value_list_text
        if (TextUtils.isEmpty(spec_value_list_text)) {
            spec_value_list_text = ""
        }
        helper.setText(R.id.tv_spec_content, spec_value_list_text)

    }

    /*设置商品所在店铺 start*/
    private fun setShopItemView(
            helper: BaseViewHolder,
            shop: AbsShopModel,
            binding: ItemGoodsdetailShopBinding
    ) {
        val iv_goodsdetail_shopdesc = helper.getView<TextView>(R.id.iv_goodsdetail_shopdesc)
        //评分
        iv_goodsdetail_shopdesc.setText(Html.fromHtml(shop.absShopIntro))
        binding.model = shop
        val rb_goodsdetail_shop_star = helper.getView<RatingBar>(R.id.rb_goodsdetail_shop_star)
        rb_goodsdetail_shop_star.rating = shop.absShopCredit.toFloat()

        val tv_goodsdetail_starvalue = helper.getView<TextView>(R.id.tv_goodsdetail_starvalue)
        tv_goodsdetail_starvalue.text = String.format("%.1f", shop.absShopCredit)

        //关注数
        helper.setText(R.id.tv_goods_collect_cnt, "${shop.absShopCollectCnt}")
        //商品数
        helper.setText(R.id.tv_goods_goods_cnt, "${shop.absShopGoodsNum}")
        //销量
        helper.setText(R.id.tv_goods_xiaoliang_cnt, "99")
    }

    /*设置商品评论 start*/
    private fun setCommentsItemView(
            helper: BaseViewHolder,
            goods: AbsGoodsModel,
            commentResultModel: ResultModel<ArrayList<Goods2CommenModel>>,
            binding: ItemGoodsdetailComments2Binding
    ) {

        //评论数
        val tv_commens_cnt = helper.getView<TextView>(R.id.tv_commens_cnt)
        tv_commens_cnt.text = String.format(ResString.get(R.string.评论_数), "${commentResultModel.totalData}")

        //好评率
        val tv_commens_haopinglv = helper.getView<TextView>(R.id.tv_commens_haopinglv)
        tv_commens_haopinglv.text = String.format(ResString.get(R.string.好评率_数), "${goods.absGoodsGrade}%")

        val commensDatas = arrayListOf<Goods2CommenModel>()
        if (commentResultModel.data != null) {
            val arrayList = commentResultModel.data!!
            if (!arrayList.isNullOrEmpty()) {
                commensDatas.addAll(arrayList)
            }
        }
        if (!commensDatas.isNullOrEmpty()) {
            val goods2CommenModel = commensDatas[0]

            //用户评论
            val ll_commens_userinfo = helper.getView<LinearLayout>(R.id.ll_commens_userinfo)
            val cv_commens_head = helper.getView<ImageView>(R.id.cv_commens_head)
            val tv_commens_name = helper.getView<TextView>(R.id.tv_commens_name)
            val tv_commens_content = helper.getView<TextView>(R.id.tv_commens_content)
            ll_commens_userinfo.visibility = View.VISIBLE
            WImageLoader.displayImage(goods2CommenModel.userFace, cv_commens_head)
            tv_commens_name.text = goods2CommenModel.userName
            tv_commens_content.text = goods2CommenModel.content

            val images = arrayListOf<String>()
            if (!(goods2CommenModel!!.images.isNullOrEmpty())) {
                for (i in 0 until goods2CommenModel!!.images!!.size) {
                    images.add(goods2CommenModel!!.images!![i])
                    if (i >= 4) {
                        break
                    }
                }
            }
            if (!images.isNullOrEmpty()) {
                val recyclerView = helper.getView<RecyclerView>(R.id.rv_commens)
                recyclerView.visibility = View.VISIBLE
                val adapter2 = GoodsCommensItemAdapter(images)
                recyclerView.run {
                    layoutManager = GridLayoutManager(context, 4)
                    adapter = adapter2
                    if (itemDecorationCount == 0) {
                        addItemDecoration(GridSpacingItemDecoration(4, DisplayUtils.dip2px(context, 5f), false))
                    }
                }
            }
        }
    }


    /*设置商品信息 start*/
    private fun setGalleryItemView(
            helper: BaseViewHolder,
            item: ArrayList<Goods2GalleryBean>
    ) {
        helper.itemView.visibility = if (list.isNullOrEmpty()) {
            View.GONE
        } else {
            View.VISIBLE
        }
        val banner = helper.getView<Banner<*,*>>(R.id.banner_goodsdetail_info)
//        if (item.size == 1) {
//            item.addAll(item)
//        }
        val tv_banner_info = helper.getView<TextView>(R.id.tv_banner_info)
        tv_banner_info.text = "1/${item.size}"
        banner.setLoopTime(2000)//设置动画时间
        banner.isAutoLoop(true)
        banner.adapter=BannerImageImlAdapter(item)
        banner.indicator=CircleIndicator(context)
        //点击事件
        banner.setOnBannerListener { data, position ->
//            activity.to<GoodsDetail2Activity>().showGallay(item.map { Uri.parse(it.big) }, position)
            ImageWatchHelper.show(context = context,anyList = item,position = 0)
        }
        banner.addOnPageChangeListener(object :OnPageChangeListener{
            override fun onPageScrollStateChanged(state: Int) {
            }

            override fun onPageScrolled(position: Int, positionOffset: Float, positionOffsetPixels: Int) {
            }

            override fun onPageSelected(position: Int) {
                tv_banner_info.text = "${position + 1}/${item.size}"
            }

        })
        banner.start()

    }

    /*设置商品信息 start*/
    private fun setDetailItemView(
            helper: BaseViewHolder,
            goods: AbsGoodsModel,
            binding: ItemGoodsdetailDetailBinding) {

        //商品名称
        val tv_goodsdetail_goodsname = helper.getView<TextView>(R.id.tv_goodsdetail_goodsname)
        tv_goodsdetail_goodsname.text = goods.absGoodsName

        //当前币种
        val tv_goodsdetail_bizhong = helper.getView<TextView>(R.id.tv_goodsdetail_bizhong)
        val bizhong = CountrysRepository.getCurrenCurrencyShort().toUpperCase()
        tv_goodsdetail_bizhong.tag = CountrysRepository.getCurrencySelect()
        tv_goodsdetail_bizhong.text = "${bizhong} >"


        //销售量
        val tv_goodsdetail_xiaoliang = helper.getView<TextView>(R.id.tv_goodsdetail_xiaoliang)
        tv_goodsdetail_xiaoliang.text = "${goods.absGoodsSellCount}"

        //商品价格
        val tv_goodsdetail_price = helper.getView<TextView>(R.id.tv_goodsdetail_price)

        CurrencyPriceBuilder3().run {
            textView = tv_goodsdetail_price
            price = goods.absGoodsPrice
            priceList = goods.absGoodsPriceList
            build14_18()
        }


        tv_goodsdetail_bizhong.setOnClickListener {
            ChoiceCurrencyDialog(context).run {
                select_currency = tv_goodsdetail_bizhong.tag as CurrencyModel
                setSureClick<CurrencyModel> { currencyModel ->
                    tv_goodsdetail_bizhong.tag = currencyModel
                    tv_goodsdetail_bizhong.text = "${currencyModel.currency_short.toUpperCase()} >"
                    CurrencyPriceBuilder3().run {
                        textView = tv_goodsdetail_price
                        //找到符号
                        currencyMark = currencyModel.currency_mark
                        currencyShort = currencyModel.currency_short
                        //找到其中价格
                        priceList = goods.absGoodsPriceList
                        build14_18()
                    }
                }
                this
            }.show()
        }


    }


}